import { _decorator, Acceleration, Component, instantiate, Node } from 'cc';
import DataManager from '../../Global/DataManager';
import { JoyStickManager } from '../../UI/JoyStickManager';
import { EntityTypeEnum, IActor, InputTypeEnum } from '../../Common';
import { EntityManager } from '../../Base/EntityManager';
import { ActorStateMachine } from './ActorStateMachine';
import { EntityStateEnum } from '../../Enum';
import { WeaponManager } from '../Weapon/WeaponManager';
import { rad2Angle } from '../../Utils';
const { ccclass, property } = _decorator;
//动作管理类
@ccclass('ActorManager')
export class ActorManager extends EntityManager {
    //武器管理器
    private wm: WeaponManager

    init(data: IActor) {
        //设置状态机
        this.fsm = this.addComponent(ActorStateMachine)
        this.fsm.init(data.type)
        //播放待机动画
        this.state = EntityStateEnum.Idle

        //武器预制体
        const prefab = DataManager.Instance.prefabMap.get(EntityTypeEnum.Weapon1)
        const weapon = instantiate(prefab)
        //设置预制体到角色节点下
        weapon.setParent(this.node)
        //动态添加一个脚本
        this.wm = weapon.addComponent(WeaponManager)
        this.wm.init(data)
    }

    //每帧去读摇杆有没有变化，如果有变化就把变化信息加入到数据管理器中
    tick(dt: number): void {
        //先判断玩家是不是真的在操作摇杆
        if (DataManager.Instance.jm.input.length()) {
            //获取摇杆移动的值，也就是归一化后的{1,0}
            const { x, y } = DataManager.Instance.jm.input
            //喂输入数据给数据管理器
            DataManager.Instance.applyInput({
                id: 1,
                type: InputTypeEnum.ActorMove,
                direction: {
                    x, y
                },
                dt
            })

            console.log(DataManager.Instance.state.actors[0].position)

            //状态切换
            this.state = EntityStateEnum.Run
        } else {
            this.state = EntityStateEnum.Idle
        }

    }

    //执行动作
    render(data: IActor) {
        const { direction, position } = data
        //让角色移动
        this.node.setPosition(position.x, position.y)

        //看下角色当前方向，如果不等于0就是要翻转面向
        if (direction.x !== 0) {
            //如果朝向大于0，就左边，否则就是-1右边，用缩放改变朝向，方向，面向
            this.node.setScale(direction.x > 0 ? 1 : -1, 1)
        }

        //旋转枪，计算出斜边
        const side = Math.sqrt(direction.x ** 2 + direction.y ** 2)
        //计算出夹角
        const rad = Math.asin(direction.y / side)
        //弧度转角度
        const angle = rad2Angle(rad)

        //设置角度
        this.wm.node.setRotationFromEuler(0, 0, angle)
    }

}


